package kr.go.nih.biomedi.pSEVA.bean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class RunScript {

	private String realFolder;
	private String processName;
	private ArrayList<String> inputFiles;

	private Process p = null;
	private Boolean result = false;
	private String s = "";
	
	
	public String getRealFolder() {
		return realFolder;
	}

	public void setRealFolder(String realFolder) {
		this.realFolder = realFolder;
	}

	public String getProcessName() {
		return processName;
	}

	public void setProcessName(String processName) {
		this.processName = processName;
	}

	public ArrayList<String> getInputFiles() {
		return inputFiles;
	}

	public void setInputFiles(ArrayList<String> inputFiles) {
		this.inputFiles = inputFiles;
	}
	
	public String doScript(){
		
		String FileList="";
		
		for(int i=0; i<this.getInputFiles().size(); i++)
			FileList=FileList+" "+this.getInputFiles().get(i);
				
		String strCmd = "/ldata/home/tslinux/Work/ngs-pipeline-parallel "+this.getProcessName()+" "+FileList;

		try {
			p = Runtime.getRuntime().exec(strCmd);
			StreamPrintThread errprint = new StreamPrintThread(p.getErrorStream());
			StreamPrintThread okprint = new StreamPrintThread(p.getInputStream());
			p.getOutputStream().close();
			p.getErrorStream().close();

			errprint.start();
			okprint.start();

			int rst = p.waitFor();
			
			if (0 == rst) {
				System.out.println("RunProgram success : " + strCmd);
				result = true;
			} else {
				System.out.println("RunProgram fail (rst:" + rst + ") : "
						+ strCmd);
				result = false;
			}

			BufferedReader in = new BufferedReader(new InputStreamReader(
					p.getInputStream()));

			while ((s = in.readLine()) != null) {
				System.out.println(s);
			}
		} catch (InterruptedException ie) {
			ie.printStackTrace();
			result = false;
		} catch (IOException ioe) {
			ioe.printStackTrace();
			//result = false;
		} finally {
			if (null != p) {
				p.destroy();
			}
		}
		
		if (result == true) {
			return "true";
		} else {
			return "false";
		}
	}
	
	class StreamPrintThread extends Thread {
		private BufferedReader br = null;

		public StreamPrintThread(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

		public void close() {
			try {
				if (br != null) {
					br.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public void run() {
			try {
				String line = "";
				while ((line = br.readLine()) != null) {
					System.out.println(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				close();
			}
		}
	}

	
}
